using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using pal.SvnConf.Core;

namespace pal.SvnConf.GUI
{
    public partial class MainWindow : Form
    {
        private ISvnConfigurationProvider _svnConfigurationProvider = SvnServeConfigurationFile.NULL;
        private string _configurationFile;

        public MainWindow()
        {
            InitializeComponent();
            updateUI();
        }

        private string selectAFile(string dialogTitle)
        {
            _fileOpener.ShowDialog(this);
            _fileOpener.CheckPathExists = true;
            _fileOpener.Title = dialogTitle;
            return _fileOpener.FileName;
        }

        private void updateUI()
        {
            clearDynamicUI();
            if (_configurationFile != null)
            {
                setDatasources();
                statusMessage(string.Format("Using configuration file: {0}", _configurationFile), Color.Green);
            }
            else
                statusMessage("Please choose the SVN configuration file to proceed..", Color.Red);
        }

        private void clearDynamicUI()
        {
            _pnlUserDynamicUI.Controls.Clear();
            _pnlGroupDynamicUI.Controls.Clear();
        }

        private void statusMessage(string message, Color color)
        {
            _statusMessage.ForeColor = color;
            _statusMessage.Text = message;
        }

        private void setDatasources()
        {
            _userListView.DataSource = new UsersDataSetView(_svnConfigurationProvider.Users).BindingSource;
            _groupListView.DataSource = new GroupsDataSetView(_svnConfigurationProvider.Groups).BindingSource;
            _lstAcls.DataSource = _svnConfigurationProvider.Acls;
        }

        private void OnOpenConfigurationFileClick(object sender, EventArgs e)
        {
            _configurationFile = selectAFile("Choose the SVN configuration file..");
            if (_configurationFile != null)
            {
                _svnConfigurationProvider = new SvnServeConfigurationFile(_configurationFile);
                _svnConfigurationProvider.Initialize();
            }
            updateUI();
        }

        private void OnSaveConfigurationClick(object sender, EventArgs e)
        {
            _svnConfigurationProvider.SaveChanges();
            statusMessage("Successfully saved all changes.. :)", Color.Green);
        }

        private void OnExitClick(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void OnNewUserClick(object sender, EventArgs e)
        {
            NewUserControl newUser = new NewUserControl();
            newUser.OnCreateUser += handleUserCreation;
            showUserControlInDynamicUIPanel(newUser, _pnlUserDynamicUI);
        }

        private void handleUserCreation(string userName, string password)
        {
            _svnConfigurationProvider.CreateUser(userName, password);
            updateUI();
        }

        private void OnDeleteUserClick(object sender, EventArgs e)
        {
            if (_userListView.SelectedRows.Count > 0)
                _svnConfigurationProvider.DeleteUser(
                    _userListView.SelectedRows[0].Cells[UsersDataSetView.USERNAME_COLUMN].Value.ToString());
            else
                statusMessage(
                    "Ah! First time using GUI? I can understand.. Anyways, click on me again once you figure out whom to delete..",
                    Color.Red);
            updateUI();
        }

        private void OnChangePasswordClick(object sender, EventArgs e)
        {
            string userName;

            if (_userListView.SelectedRows.Count > 0)
            {
                userName = _userListView.SelectedRows[0].Cells[UsersDataSetView.USERNAME_COLUMN].Value.ToString();
                ChangePasswordControl changePasswordControl = new ChangePasswordControl(userName);
                changePasswordControl.OnPasswordChange += handlePasswordChange;
                showUserControlInDynamicUIPanel(changePasswordControl, _pnlUserDynamicUI);
            }
            else
            {
                statusMessage("Let me know when you figure out whose password to change..", Color.Red);
                return;
            }
        }

        private void handlePasswordChange(string userName, string password)
        {
            _svnConfigurationProvider.SetPassword(userName, password);
            updateUI();
        }

        private void OnNewGroupCilck(object sender, EventArgs e)
        {
            CreateGroupControl createGroupControl = new CreateGroupControl();
            createGroupControl.OnGroupCreation += handleGroupCreation;
            showUserControlInDynamicUIPanel(createGroupControl, _pnlGroupDynamicUI);
        }

        private void handleGroupCreation(string groupName)
        {
            _svnConfigurationProvider.CreateGroup(groupName);
            updateUI();
        }

        private void OnDeleteGroupClick(object sender, EventArgs e)
        {
            if (isAnyGroupSelected())
                _svnConfigurationProvider.DeleteGroup(selectedGroupName());
            else
                statusMessage(
                    "Ah! First time using GUI? I can understand.. Anyways, click on me again once you figure out which one to delete..",
                    Color.Red);
            updateUI();
        }

        private bool isAnyGroupSelected()
        {
            return _groupListView.SelectedRows.Count > 0;
        }

        private void OnEditMembershipClick(object sender, EventArgs e)
        {
            if (isAnyGroupSelected())
            {
                GroupMembershipEditor membershipEditor =
                    new GroupMembershipEditor(selectedGroupName(), _svnConfigurationProvider);
                membershipEditor.OnMembershipChange += handleGroupMembershipChanges;
                showUserControlInDynamicUIPanel(membershipEditor, _pnlGroupDynamicUI);
            }
            else
                statusMessage(
                    "Ah! First time using GUI? I can understand.. Anyways, click on me again once you figure out which one to edit..",
                    Color.Red);
        }

        private void showUserControlInDynamicUIPanel(Control userControl, Panel dynamicUIPanel)
        {
            dynamicUIPanel.Controls.Clear();
            dynamicUIPanel.Controls.Add(userControl);
        }

        private void handleGroupMembershipChanges(string groupName, List<ISecurityPrincipal> members)
        {
            _svnConfigurationProvider.DeleteGroup(groupName);
            _svnConfigurationProvider.CreateGroup(groupName, members);
            updateUI();
        }

        private string selectedGroupName()
        {
            return _groupListView.SelectedRows[0].Cells[GroupsDataSetView.GROUPNAME_COLUMN].Value.ToString();
        }

        private void OnAclSelectionChanged(object sender, EventArgs e)
        {
            if (_lstAcls.SelectedIndex >= 0)
                _authorizationEntries.DataSource =
                    new AuthorizationEntriesDataSetView(((Acl) _lstAcls.SelectedItem).AuthorizationEntries).
                        BindingSource;
        }

        private void OnAddAclEntryClick(object sender, EventArgs e)
        {
        }

        private void OnDeleteAclEntryClick(object sender, EventArgs e)
        {
        }

        private void OnEditAclEntryClick(object sender, EventArgs e)
        {
        }

        private void OnAclMemberSelectionChanged(object sender, EventArgs e)
        {
        }
    }
}